package com.randb.easyhttp.callback;

import com.google.gson.internal.$Gson$Types;
import com.randb.easyhttp.cache.model.CacheResult;
import com.randb.easyhttp.model.ApiResult;
import com.randb.easyhttp.utils.Utils;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;

import okhttp3.ResponseBody;

/**
 * User: RandBII
 * Date: 2020/5/11
 * Description:
 */
public abstract class CallbackProxy<T extends ApiResult<R>, R> implements IType<T> {

    private Callback<R> mCallback;

    public CallbackProxy(Callback<R> callback) {
        mCallback = callback;
    }

    public Callback getCallback() {
        return mCallback;
    }

    @Override
    public Type getType() {
        Type typeArguments = null;

        if (mCallback != null) {
            Type rawType = mCallback.getRawType();
            if (List.class.isAssignableFrom(Utils.getClass(rawType, 0))
                    || Map.class.isAssignableFrom(Utils.getClass(rawType, 0))) {
                typeArguments = mCallback.getType();
            } else if (CacheResult.class.isAssignableFrom(Utils.getClass(rawType, 0))) {
                Type type = mCallback.getType();
                typeArguments = Utils.getParameterizedType(type, 0);
            } else {
                Type type = mCallback.getType();
                typeArguments = Utils.getClass(type, 0);
            }
        }

        if (typeArguments == null) {
            typeArguments = ResponseBody.class;
        }
        Type rawType = Utils.findNeedType(getClass());
        if (rawType instanceof ParameterizedType) {
            rawType = ((ParameterizedType) rawType).getRawType();
        }
        return $Gson$Types.newParameterizedTypeWithOwner(null, rawType, typeArguments);
    }

}
